package com.shenfc.fxzj.action.admin;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.shenfc.fxzj.constants.CodeConstants;
import com.shenfc.fxzj.constants.RoleTypeEnum;
import com.shenfc.fxzj.domain.*;
import com.shenfc.fxzj.service.ISysMenuService;
import com.shenfc.fxzj.service.ISysRoleRelService;
import com.shenfc.fxzj.service.ISysRoleService;
import com.shenfc.fxzj.service.ISysUserService;
import com.shenfc.fxzj.solr.BlogSolrIndex;
import com.shenfc.fxzj.util.ArrayUtils;
import com.shenfc.fxzj.util.HtmlUtil;
import com.shenfc.fxzj.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 管理员博客Controller层
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/admin/sysRole")
public class SysRoleAdminAction extends BaseAction {

    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysMenuService sysMenuService;
    @Autowired
    private ISysRoleRelService sysRoleRelService;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RedisUtil redisUtil;

//    @Autowired
//    private S blogService;

    // 博客索引
    private BlogSolrIndex blogIndex = new BlogSolrIndex();

    private static String content;

    private final static Logger log = LoggerFactory.getLogger(SysRoleAdminAction.class);

    @RequestMapping("/index")
    public ModelAndView index() throws Exception {
        return new ModelAndView("admin/sysRole/sysRoleList");
    }

    @RequestMapping("/add")
    public ModelAndView add(SysRole sysRole, String type) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("type", type);
        if (sysRole.getId() == null) {

        } else {
            SysRole bean = sysRoleService.getSysRoleById(sysRole.getId());
            mav.addObject("data", bean);
        }
        mav.setViewName("/admin/sysRole/sysRoleAdd");
        return mav;
    }

    @RequestMapping("/getMenuIdsAndBtnIds")
    @ResponseBody
    public JSONObject getMenuIdsAndBtnIds(Long roleId, HttpServletResponse response) throws Exception {
        JSONObject result = new JSONObject();
        try {
            //获取权限关联的菜单
            Long[] menuIds = null;
            List<SysMenu> menuList = sysMenuService.getMenuByRoleId(roleId);
            if (ArrayUtils.isNotEmpty(menuList)) {
                menuIds = new Long[menuList.size()];
                int i = 0;
                for (SysMenu item : menuList) {
                    menuIds[i] = item.getId();
                    i++;
                }
            }
            //获取权限下关联的按钮
            Long[] btnIds = null;
            List<SysRoleRel> btnList = sysRoleRelService.getRoleRelByRoleId(roleId, RoleTypeEnum.BTN.getKey());
            if (ArrayUtils.isNotEmpty(btnList)) {
                btnIds = new Long[btnList.size()];
                int i = 0;
                for (SysRoleRel item : btnList) {
                    btnIds[i] = item.getObjId();
                    i++;
                }
            }
            result.put("menuIds", menuIds);
            result.put("btnIds", btnIds);
            result.put("success", true);
        } catch (Exception e) {
            log.error("获取权限信息失败", e);
            result.put("success", false);
            result.put("msg", "获取权限信息失败");
        }
        return result;
    }

    /**
     * 添加或者修改博客信息
     */
    @RequestMapping("/save")
    @ResponseBody
    public JSONObject save(SysRole sysRole, Long[] menuIds, Long[] btnIds, HttpServletResponse response) throws Exception {
        JSONObject result = new JSONObject();
        try {
            if (sysRole.getId() == null) {
                sysRole.setStatus(CodeConstants.YES);
                sysRole.setCreateTime(new Date());
                sysRole.setCreateUserId(getShiroSessionUserId());
                sysRoleService.addRole(sysRole, menuIds, btnIds);
            } else {
                sysRoleService.updateRole(sysRole, menuIds, btnIds);
                List<SysUser> sysUserList = sysUserService.getSysUsersByRoleId(sysRole.getId());
                if (ArrayUtils.isNotEmpty(sysUserList)) {
                    for (SysUser sysUser : sysUserList) {
                        redisUtil.del(CodeConstants.REDIS_SHIRO_CACHE + sysUser.getUserName());
                    }
                }
            }
            result.put("success", true);
            result.put("msg", "保存成功");
        } catch (Exception e) {
            log.error("角色保存失败", e);
            result.put("success", false);
            result.put("msg", "保存失败");
        }
        return result;
    }

    /**
     * 分页查询博客信息
     */
    @RequestMapping("/list")
    public void list(PageBean pageBean, SysRole sysRole, HttpServletResponse response) {
        DataGridJson<SysRole> dataGridJson = new DataGridJson<SysRole>();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("roleName", sysRole.getRoleName());
            PageInfo<SysRole> pageInfo = sysRoleService.querySysRolePage(map, pageBean);
            List<SysRole> sysRoleList = pageInfo.getList();
            dataGridJson.setData(sysRoleList);
            dataGridJson.setCount(pageBean.getRecTotal());
            HtmlUtil.writerJson(response, dataGridJson);
        } catch (Exception e) {
            dataGridJson.setCode(1);
            dataGridJson.setMsg("请求出现异常，请联系管理员！");
            HtmlUtil.writerJson(response, dataGridJson);
        }
    }

    /**
     * 删除博客信息
     */
    @RequestMapping("/delete")
    @ResponseBody
    public JSONObject delete(@RequestParam(value = "ids[]", required = false) Long[] ids, String page, HttpServletResponse response) throws Exception {
        JSONObject result = new JSONObject();
//        try {
//            if (ids != null && ids.length > 0) {
//                for (Long i : ids) {
//                    Blog blog = blogService.getBlogById(i);
//                    blogIndex.deleteIndex(blog.getUuid()); // 添加博客索引
//                }
//                blogService.deleteBlogBatch(ids);
//            }
//            result.put("success", true);
//            result.put("msg", "删除成功");
//        } catch (Exception e) {
//            result.put("success", false);
//            result.put("msg", "删除失败");
//        }
        return result;
    }

    @RequestMapping("/updateStatus")
    @ResponseBody
    public JSONObject delete(Long id, String status, HttpServletResponse response) throws Exception {
        JSONObject result = new JSONObject();
        try {
            sysRoleService.updateStatus(id, status);
            result.put("success", true);
            result.put("msg", "修改成功");
        } catch (Exception e) {
            log.error("修改活动状态失败", e);
            result.put("success", false);
            result.put("msg", "修改失败");
        }
        return result;
    }
}
